# -*- coding:utf-8 -*-
from framework.interface.abstract_api import AbstractApi
from zhipuai import ZhipuAI
from flask import request
import requests
from marshmallow import Schema, fields, validate
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from collections import namedtuple
from flask import Response
from PIL import Image
import io
import uuid


class AiImport(AbstractApi):
    """
    接口：Test
    文件名输入：test
    该接口访问地址为：http://127.0.0.1:5000/v1/ai-import
    输入：
    功能：a
    通用性文件处理能力  对文件的目前字段情况进行扫描
    输出：
    """

    class PostSchema(Schema):
        zhipucontent = fields.Str(required=False)

    def handle_post_request(self):
        # 联网
        try:
            zhipucontent = request.get_json()['zhipucontent']
            output2 = self.recognize_lianwang(zhipucontent)
            return output2
        # 识图
        except:
            message = False
            img_url = self.save_img_and_get_url()
            print(message)
            output2 = self.recognize_image(img_url)
            return output2

    # 业务1 保存圖片
    def save_img_and_get_url(self):
        # 假设 img_data 是从前端或其他来源获取的 FileStorage 对象
        img_data = self.get_files("file")
        # 从 FileStorage 对象中读取字节数据
        img_bytes = img_data.read()
        # 将字节数据转换为PIL的Image对象
        image = Image.open(io.BytesIO(img_bytes))

        # 检查图片是否为RGBA模式，如果是则转换为RGB
        if image.mode == 'RGBA':
            # 使用白色背景创建一个新的RGB图像
            background = Image.new('RGB', image.size, (255, 255, 255))
            # 粘贴RGBA图像到RGB背景图上，忽略透明度信息
            background.paste(image, mask=image.split()[3])  # 3 表示Alpha通道
            image = background
        # 保存图片到文件系统
        name = uuid.uuid4()
        image.save(f'./static/{name}.jpg', 'JPEG')
        return str(name) + ".jpg"

    # 业务二 质谱推理 图片
    def recognize_image(self, image_url):
        print("测试")

        base_url = "http://106.53.97.117:7777/static/" + image_url
        api_key = "88a9abd4972f12772fa9e0e5aa03e18f.81dptUcRAzjXordE"
        client = ZhipuAI(api_key=api_key)
        response = client.chat.completions.create(
            model="glm-4v",  # 填写需要调用的模型名称
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": "图里有什么,详细一点"
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": base_url
                            }
                        }
                    ]
                }
            ]
        )
        try:
            print(response.choices[0].message)
            return {"content": response.choices[0].message.content, "url": image_url}
        except:
            return "失败"

    # 业务二 质谱推理 联网
    def recognize_lianwang(self, text):
        api_key = "00801e0d13fe4d4098058f97112163e9.JHpdnQbiri0xEEY8"
        client = ZhipuAI(api_key=api_key)
        response = client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=[
                {"role": "user", "content": text}
            ],
        )
        try:
            return {"content": response.choices[0].message.content}
        except:
            return "失败"
